
import requests
import json


def getAccess_token(appkey='dingcf30bzefpgrssqth', appsecret='AUL9EK9zud74RH-gbC4wSMPa67srYQ1NFIePT5cLPRFF4H3QQ0Hi5E3qBcfLTaKG'):
    appkey = 'dingcf30bzefpgrssqth'
    appsecret = 'AUL9EK9zud74RH-gbC4wSMPa67srYQ1NFIePT5cLPRFF4H3QQ0Hi5E3qBcfLTaKG'
    url = 'https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s' % (appkey, appsecret)

    headers = {
        'Content-Type': "application/x-www-form-urlencoded"
    }
    data = {'appkey': appkey,
            'appsecret': appsecret}
    r = requests.request('GET', url, data=data, headers=headers)
    access_token = r.json()["access_token"]
    return access_token


def getMedia_id(path=r'C:\recruitment\media\resume_upload\下载_4.docx'):
    access_token = getAccess_token()  # 拿到接口凭证
    path = r'C:\recruitment\media\resume_upload\71-Alex YANG个人简历.docx'  # 文件地址
    url = 'https://oapi.dingtalk.com/media/upload?access_token=%s&type=file' % access_token
    files = {'media': open(path, 'rb')}
    data = {'access_token': access_token,
            'type': 'file'}
    response = requests.post(url, files=files, data=data)
    json = response.json()
    return json["media_id"]


def SendFile(chatid='', content=''):
    access_token = getAccess_token()

    media_id = getMedia_id()
    # chatid = 'chat51b9258f58adf9bf1ef1fe4223b63a57'  # 通过jsapi工具获取的群聊id
    url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
    header = {
        'Content-Type': 'application/json'
    }
    data = {'access_token': access_token,
            'chatid': chatid,
            'msg': {
                'msgtype': 'file',
                'file': {'media_id': media_id},
                'filename': 'a.docx'
            }}
    r = requests.request('POST', url, data=json.dumps(data), headers=header)
    print(r.json())
    msgtype = 'text'
    values = {
        "chatid": chatid,
        "msgtype": msgtype,
        msgtype: {
            "content": content
        }
    }
    values = json.dumps(values)
    data = requests.post(url, values)
    errmsg = json.loads(data.text)['errmsg']
    print(errmsg)


if __name__ == '__main__':

    SendFile(chatid='chat51b9258f58adf9bf1ef1fe4223b63a57', content='测试')


